import csv
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from datetime import datetime
import random
from http import HTTPStatus
from dashscope import Generation
import dashscope
import requests

requests.Session().mount('https://',
                         requests.adapters.HTTPAdapter(max_retries=3,
                                                       pool_maxsize=10,
                                                       pool_block=True))
requests.adapters.DEFAULT_RETRIES = 3
requests.adapters.DEFAULT_POOL_TIMEOUT = 600  # 设置超时时间为600秒

# 假设call_with_messages是调用DashScope API的函数

# 可以在这里加入更多的错误处理逻辑，如记录日志、提示用户等
# 设置 DashScope API 密钥
dashscope.api_key = "sk-51d751795ffe46a5a053bfc25d2865c6"


def call_with_messages(content):
    messages = [{'role': 'system',
                 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': content}]
    response = Generation.call(model="qwen-turbo",
                               messages=messages,
                               seed=random.randint(1, 10000),
                               result_format='message')

    if response.status_code == HTTPStatus.OK:
        try:
            return response.output.choices[0].message.content
        except Exception as e:
            print("Error processing response:", e)
            return "Error fetching AI suggestion."
    else:
        print(f"Request failed with status: {response.status_code},"
              f" code: {response.code}, message: {response.message}")
        return "Failed to fetch AI suggestion."


class FinanceTrackerApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("个人理财小软件")
        self.geometry("500x400")

        # 初始化跟踪变量

        self.total_income = 0
        self.total_expense = 0
        self.income_records = []
        self.expense_records = []

        # 添加日志组件
        self.csv_filename = 'finance_records.csv'
        self.initialize_csv()
        self.log = ScrolledText(self, height=10)
        self.log.grid(row=4, column=0, columnspan=4, padx=10,
                      pady=10, sticky=tk.NSEW)

        # 添加描述性标签和输入框
        self.amount_label = ttk.Label(self, text="金额:")
        self.reason_label = ttk.Label(self, text="说明:")
        self.amount_entry = tk.Entry(self)
        self.reason_entry = tk.Entry(self)

        # 添加按钮
        self.income_button = tk.Button(self, text="添加收入",
                                       command=self.add_income)
        self.expense_button = tk.Button(self, text="添加支出",
                                        command=self.add_expense)

        # 初始化后立即更新AI建议

        # 初始化UI
        self.init_ui()

    def initialize_csv(self):
        with open(self.csv_filename, mode='w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['时间', '类型', '金额', '余额'])

    def update_csv(self, record_type, amount):
        current_balance = self.total_income - self.total_expense
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open(self.csv_filename, mode='a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow([timestamp, record_type,
                             amount, current_balance])

    def get_summary_and_suggestions(self):
        summary = f"总收入: {self.total_income}\n总支出: " \
                  f"{self.total_expense}\n总余额: " \
                  f"{self.total_income - self.total_expense}\n"
        summary += "收入详情:\n"
        for amount, reason in self.income_records:
            summary += f"金额: {amount}, 原因: {reason}\n"
        summary += "支出详情:\n"
        for amount, reason in self.expense_records:
            summary += f"金额: {amount}, 原因: {reason}\n"

        ai_input = f"请根据以下财务情况给出建议:\n{summary}"
        from requests.exceptions import ConnectTimeout

        # 假设call_with_messages是调用DashScope API的函数
        try:
            suggestion = call_with_messages(ai_input)
        except ConnectTimeout:
            suggestion = "网络连接超时，请检查您的网络设置。"
            # 可以在这里加入更多的错误处理逻辑，如记录日志、提示用户等
        return suggestion

    def update_suggestions(self):
        suggestion = self.get_summary_and_suggestions()
        # 这里需要一个控件来显示AI建议，例如一个Label或者Text控件
        # 假设我们创建了一个名为ai_suggestions_label的Label控件
        self.ai_suggestions_label.config(text=suggestion)

    def init_ui(self):
        self.amount_label.grid(row=0, column=0, pady=10, sticky=tk.E)
        self.amount_entry.grid(row=0, column=1, pady=10)
        self.reason_label.grid(row=1, column=0, pady=10, sticky=tk.E)
        self.reason_entry.grid(row=1, column=1, pady=10, columnspan=2)

        # 添加总收入、总支出、余额的标签
        self.total_income_label = ttk.Label(self, text="总收入: 0.00")
        self.total_income_label.grid(row=2, column=0,
                                     pady=10, sticky=tk.W)
        self.total_expense_label = ttk.Label(self, text="总支出: 0.00")
        self.total_expense_label.grid(row=2, column=1,
                                      pady=10, sticky=tk.W)
        self.balance_label = ttk.Label(self, text="余额: 0.00")
        self.balance_label.grid(row=2, column=2, pady=10, sticky=tk.W)

        # 注意：这里需要添加一个显示AI建议的Label或Text控件，并将其初始化
        self.ai_suggestions_label = ttk.Label(self, text="等待AI建议...")
        self.ai_suggestions_label.grid(row=5, column=0,
                                       columnspan=4, pady=10)

        self.income_button.grid(row=0, column=3, pady=10)
        self.expense_button.grid(row=1, column=3, pady=10)

        self.update_suggestions()
        self.update_labels()

    def add_income(self):
        self.add_transaction(True)

    def add_expense(self):
        self.add_transaction(False)

    def add_transaction(self, is_income):
        amount_str = self.amount_entry.get().strip()
        reason = self.reason_entry.get().strip()

        if amount_str.replace('.', '', 1).isdigit():
            amount = float(amount_str)
            if is_income:
                self.total_income += amount
                self.income_records.append((amount, reason))
            else:
                self.total_expense += amount
                self.expense_records.append((amount, reason))

            self.update_labels()
            self.log_transaction(is_income, amount, reason)
            # 假设你有这样一个方法专门用来记录交易日志
            self.update_suggestions()

        else:
            tk.messagebox.showerror("输入错误", "请输入有效的金额数字。")

    def log_transaction(self, is_income, amount, reason):
        # 记录单个收支事件到日志
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_message = f"{timestamp} - {'收入' if is_income else '支出'}" \
                      f"金额: {amount}, 原因: {reason}\n"

        self.log.insert(tk.END, log_message)
        self.log.see(tk.END)  # 使滚动条自动滚动到底部

    def clear_entries(self):
        self.amount_entry.delete(0, tk.END)
        self.reason_entry.delete(0, tk.END)

    def update_labels(self):

        # 更新UI上的总收入、总支出和余额标签，不再向日志写入信息
        balance = self.total_income - self.total_expense
        self.total_income_label.config(text=f"总收入: "
                                            f"{self.total_income:.2f}")
        self.total_expense_label.config(text=f"总支出: "
                                             f"{self.total_expense:.2f}")
        self.balance_label.config(text=f"总余额: {balance:.2f}")


if __name__ == "__main__":
    app = FinanceTrackerApp()
    app.mainloop()
    from requests.exceptions import ConnectTimeout
